<?php

namespace app\index\service;

use app\common\model\Trade;
use app\index\dao\TradeDao;
use app\index\model\UM as UM;
use ary\Ary;
use think\Collection;
use think\exception\ValidateException;

/**
 * Class SourceOrderService
 * @package app\index\service
 */
class SourceOrderService
{
    // dao
    private TradeDao $tradeDao;

    public function __construct(TradeDao $tradeDao)
    {
        $this->tradeDao = $tradeDao;
    }

    /**
     * @param UM $user
     * @param $sourceStatus
     * @param $sourceType
     * @param int|null $page
     * @param int|null $page_size
     * @return Collection
     */
    public function index(UM $user, $sourceStatus, $sourceType, ?int $page = null, ?int $page_size = null): Collection
    {
        $memberId = $user->id;

        return $this->tradeDao->selectSourceTrade($memberId, $sourceStatus, $sourceType, $page, $page_size);
    }

    /**
     * 查询
     * @param UM|null $user
     * @param int $id
     * @return Trade
     */
    public function read(UM $user, int $id): ?Trade
    {

        $record = $this->tradeDao->findSourceTrade($id);

        if (!$record) {
            throw new ValidateException('该订单不存在');
        }

        if ($record->memberId != $user->id) {
            return null;
        }

        // 查询购买该案源总计花费的获客卡数量
        $record->sumCard = $this->tradeDao->sumSourceTradePayMoney($record->sourceId);

        $this->flushSource($record);

        return $record;
    }

    public function modify(UM $user, int $id, array $params): Trade
    {
        $record = Trade::where('id', $id)->find();

        if (is_null($record)) {
            throw new ValidateException('找不到该订单');
        }

        if ($record->memberId != $user->id) {
            throw new ValidateException('您不能操作该订单');
        }

        if (isset($params['sourceStatus']) && !in_array($params['sourceStatus'], [Trade::ARY_INVITING, Trade::ARY_COMPLETED])) {
            throw new ValidateException('请选择正确的邀约状态');
        }

        $allowField = ['sourceStatus'];
        $this->tradeDao->updateActive($record, $params, $allowField);

        return $record;
    }

    /**
     * 更新案源信息
     * @param Trade $record
     * @return void
     */
    private function flushSource(Trade $record)
    {

        $attach = $record->attach;
        $source_id = $attach['source']['source_id'] ?? null;
        if (not_blank($source_id)) {
            $data = ['source_id' => $source_id];
            $response = $this->getAry()->getSourceDetail($data);
            if ($response->isSuccess()) {
                $source = $response->getDecodeContents()['data'];
                $attach['source'] = $source;
                $record->attach = $attach;
                $record->save();
            }
        }
    }

    private function getAry(): Ary
    {
        return app(Ary::class);
    }
}
